package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.dto.StudentAddRequest;
import cc.eddic.practice.spring.dto.StudentResponse;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import cc.eddic.practice.spring.repository.StudentRepository;
import java.util.NoSuchElementException;


@Slf4j
@RestController
@RequestMapping("/api/students")
public class StudentRestController {
    public StudentRestController(StudentRepository repository){this.repository = repository;}


    @PostMapping
    public HttpEntity<?> add(@RequestBody final StudentAddRequest model){
        val student = repository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(student.getId()).toUri()).build();
    }

    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id){
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }


    @GetMapping("/{id}")
    public HttpEntity<StudentResponse> get(@PathVariable("id") final long id){
        if(log.isDebugEnabled()) log.debug("id= {}", id);
        val student = repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(StudentResponse.from(student));
    }

    @GetMapping
    public HttpEntity<Page<StudentResponse>> getAll(@PageableDefault(size = 1,page = 0) Pageable pageable) {
        log.debug("size = {} ,page = {}",pageable.getPageSize(),pageable.getPageNumber());
        return ResponseEntity.ok(repository.findAll(pageable).map(StudentResponse::from));
    }

    private  final StudentRepository repository;
}
